package com.zw.yzk.kabu.presenter;

import android.support.v7.app.AppCompatActivity;
import com.app.common.download.Download;
import com.app.common.download.ProgressListener;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.base.BaseApplication;
import com.zw.yzk.kabu.base.BaseSubscriber;
import com.zw.yzk.kabu.data.network.entity.Entity;
import com.zw.yzk.kabu.data.network.entity.SkinPackageEntity;
import com.zw.yzk.kabu.data.network.task.SkinBuyFreeTask;
import com.zw.yzk.kabu.data.network.task.SkinDownloadTask;
import com.zw.yzk.kabu.data.network.task.SkinPackageTask;
import com.zw.yzk.kabu.domain.repository.UseCase;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.mapper.SkinMapper;
import com.zw.yzk.kabu.model.SkinModel;
import com.zw.yzk.kabu.skin.LocalSkinManager;
import com.zw.yzk.kabu.view.view.SkinPackageView;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import skin.support.SkinCompatManager;

import javax.inject.Inject;
import javax.inject.Named;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;

/**
 * Created by skydar on 2017/4/14.
 */

public class SkinPackagePresenter implements Presenter {

    private UseCase useCase;
    private UseCase useCase0;
    private UseCase useCase1;
    private AppCompatActivity activity;
    private SkinPackageView view;
    private SkinMapper mapper;

    private SkinModel skinModel;

    private int btnStatusIndex;


    @Inject
    public SkinPackagePresenter(@Named("skinPackageUseCase") UseCase useCase,
                                @Named("skinBuyFreeUseCase") UseCase useCase0,
                                @Named("skinDownloadUseCase") UseCase useCase1,
                                AppCompatActivity activity, SkinMapper mapper) {
        this.useCase = useCase;
        this.useCase0 = useCase0;
        this.useCase1 = useCase1;
        this.activity = activity;
        this.mapper = mapper;
    }

    public void setView(SkinPackageView view){
        this.view = view;
    }

    @Override
    public void resume() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {
        if(useCase != null) useCase.unSubscribe();
        if(useCase0 != null) useCase0.unSubscribe();
        if(useCase1 != null) useCase1.unSubscribe();
        if(downloader != null) downloader.cancel();
    }

    public void getSkinPackage(int categoryId) {
        useCase.execute(new Subscriber(activity), new SkinPackageTask(categoryId) );
    }

    private class Subscriber extends BaseSubscriber<SkinPackageEntity> {

        public Subscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public String addErrorMessage() {
            return BaseApplication.getInstance().getResources().getString(R.string.get_skin_failed);
        }

        @Override
        public void onNext(SkinPackageEntity entity) {
            super.onNext(entity);
            skinModel = mapper.transfer(entity);
            initSkinState(skinModel);
            view.showSkinPackage(skinModel);
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            view.fetchFailed();
        }

        @Override
        public void onCompleted() {
            super.onCompleted();
            LoadingDialogManager.getInstance().dismissLoadingDialog();
        }
    }


    private Download downloader;

    private class DownloadSubscriber extends BaseSubscriber<Download> {

        public DownloadSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public String addErrorMessage() {
            return BaseApplication.getInstance().getResources().getString(R.string.get_skin_failed);
        }

        @Override
        public void onNext(final Download download) {
            super.onNext(download);

            downloader = download;
            download.setProgressListener(new ProgressListener() {
                @Override
                public void onProgress(Download download, long bytesRead, long totalBytesRead, long contentLength) {
                    float progress = (float)totalBytesRead/contentLength;
                    DecimalFormat df = new DecimalFormat("#.00");
                    view.showProgress(df.format(progress * 100) + "%" );
                    view.showBtnState(1);
                }
            });
            download.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if(response.isSuccessful()){

                        view.showBtnState(2);
                        view.showDownloadComplete();
                        LocalSkinManager.getInstance().addSkin(skinModel.getId(), downloader.file());

                    }else{
                        view.showDownloadError();
                        view.showBtnState(0);
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    if(t instanceof IOException){
                        if( "Canceled".equals(t.getMessage()) ){
                            view.onDownloadCanceled();
                            view.showBtnState(0);
                            return;
                        }
                    }
                    view.showDownloadError();
                    view.showBtnState(0);
                }
            });
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            view.fetchFailed();
        }

        @Override
        public void onCompleted() {
            super.onCompleted();
            LoadingDialogManager.getInstance().dismissLoadingDialog();
        }
    }

    private void initSkinState(SkinModel model){
        File file = LocalSkinManager.getInstance().getSkinFile(model.getId());
        if(file != null && file.exists()){

            if(LocalSkinManager.getInstance().getCurrentSkin().equals(
                    LocalSkinManager.getInstance().generateName(model.getId(), model.getName()))
            ) {
                view.showBtnState(3);
            }else{
                view.showBtnState(2);
            }

        }else{
            view.showBtnState(0);
        }

    }

    public void download() {
        if(skinModel == null){
            view.showBtnState(0);
            view.skinPackageNotReady();
            return;
        }
        if(skinModel.getDiscountedPrice() == 0){

            BaseSubscriber<Entity> subscriber = new BaseSubscriber<Entity>(activity){
                @Override
                public String addErrorMessage() {
                    return BaseApplication.getInstance().getResources().getString(R.string.get_skin_failed);
                }

                @Override
                public void onNext(Entity entity) {
                    super.onNext(entity);
                    useCase1.execute(new DownloadSubscriber(activity),
                            new SkinDownloadTask(skinModel.getSourceUrl(), LocalSkinManager.getInstance().getSkinTempFile(skinModel))
                    );
                }

                @Override
                public void onCompleted() {
                    super.onCompleted();
                    LoadingDialogManager.getInstance().dismissLoadingDialog();
                }
            };
            useCase0.execute(subscriber, new SkinBuyFreeTask(skinModel.getId()));
        }
    }



    public void cancelDownload() {
        if(downloader != null){
            downloader.cancel();
        }
    }

    public void loadSkin() {

        String name =  LocalSkinManager.getInstance().getSkinName(skinModel.getId());
        if(name == null){
            initSkin();
            return ;
        }

        SkinCompatManager.getInstance().loadSkin(name, new SkinCompatManager.SkinLoaderListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess() {
                view.showBtnState(3);
                LocalSkinManager.getInstance().currentSkin(skinModel.getId());
            }

            @Override
            public void onFailed(String errMsg) {
                // 删除皮肤包
                initSkin();
            }
        });
    }

    public void initSkin(){
        if(skinModel == null) return;
        LocalSkinManager.getInstance().deleteSkin(skinModel.getId());
        view.showBtnState(0);
    }

}
